package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.domain.TechColorAuditingReports.TechColorAuditingReports;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.CustomerService;
import com.ugoodtech.mdcc.web.dto.CustomerStatResponse;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;

@Api(description = "满意度报告接口")
@RestController
@RequestMapping("warningprocessing")
public class WarningProcessing extends BaseController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    @Autowired
    private StationCustomerReportRepository stationCustomerReportRepository;

    @Autowired
    private CustomerManageNoteRepository customerManageNoteRepository;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private CustomReportSmsRepository customReportSmsRepository;

    //    @ApiOperation("获取低于60分常规报告")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
//            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
//    })
//    @RequestMapping(value = "/getWarningReport", method = RequestMethod.GET)
    public JsonResponse getWarningReport(Pageable pageable,
                                         @ApiParam("登陆用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                         @ApiParam(value = "状态:false未处理 true已处理") @RequestParam(value = "type", required = false) Boolean type,
                                         @ApiParam(value = "城市") @RequestParam(value = "city", required = false) String city,
                                         @ApiParam(value = "站点类型") @RequestParam(value = "category", required = false) String category,
                                         @ApiParam(value = "品牌") @RequestParam(value = "brand", required = false) String brand,
                                         @ApiParam(value = "维修站名称关键字") @RequestParam(value = "stationName", required = false) String stationName,
                                         @ApiParam(value = "技术人员名称关键字") @RequestParam(value = "userName", required = false) String userName,
                                         @ApiParam(value = "维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum) {
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        ModuleAuthority moduleAuthority = moduleAuthorityRepository.findByName(Constants.SIXTY_WARNING);
        boolean tf = user.getAuthorities().contains(moduleAuthority);
        if (tf == false) {
            return JsonResponse.errorResponseWithError("抱歉", "没有权限查看60分预警处理");
        }
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
//        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.score.lt("60"));
        if (StringUtils.isNotEmpty(stationNum)) {
            builder.and(qCustomerRegularReport.regularReport.station.stationNum.like("%" + stationNum + "%"));
        }
        if (type != null) {
            builder.and(qCustomerRegularReport.managed.eq(type));
        }
        if (StringUtils.isNotEmpty(city)) {
            builder.and(qCustomerRegularReport.regularReport.station.city.eq(city));
        }
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qCustomerRegularReport.regularReport.station.category.eq(category));
        }
        if (StringUtils.isNotEmpty(brand)) {
            builder.and(qCustomerRegularReport.regularReport.station.brand.eq(brand));
        }
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qCustomerRegularReport.regularReport.station.name.like("%" + stationName + "%"));
        }
        if (StringUtils.isNotEmpty(userName)) {
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            booleanBuilder.and(qUserProfile.user.userType.ne(UserType.admin));
            booleanBuilder.and(qUserProfile.user.userType.ne(UserType.customer));
            List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll();
            Long[] userIds = new Long[userProfileList.size()];
            for (int i = 0; i < userProfileList.size(); i++) {
                userIds[i] = userProfileList.get(i).getUser().getId();
            }
            builder.and(qCustomerRegularReport.regularReport.user.id.in(userIds));
        }
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<CustomerRegularReport> customerRegularReports = customerRegularReportRepository.findAll(builder, pageable);
        List<TechColorAuditingReports> reportsList = toResponse(customerRegularReports.getContent());
        Page<TechColorAuditingReports> page = new PageImpl(reportsList, pageable, customerRegularReports.getTotalElements());
        return JsonResponse.successResponseWithPageData(page);
    }

    private List<TechColorAuditingReports> toResponse(List<CustomerRegularReport> customerRegularReports) {
        List<TechColorAuditingReports> colorAuditingReportsList = new ArrayList<>();
        for (CustomerRegularReport report : customerRegularReports) {
            TechColorAuditingReports response = new TechColorAuditingReports();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
            response.setDateTime(simpleDateFormat.format(report.getUpdateTime()));
            Station station = report.getRegularReport().getStation();
            response.setId(report.getCustomerReport().getId());
            if (report.isManaged()) {
                response.setReaded(true);
                response.setAuditNote(report.getManageNote());
            } else {
                response.setReaded(false);
                response.setAuditNote("");
            }
            if (station != null) {
                if (StringUtils.isNotEmpty(station.getCity())) {
                    if (StringUtils.isNotEmpty(station.getProvince()) && StringUtils.isNotEmpty(station.getCity())) {
                        response.setCity(station.getProvince() + station.getCity());
                    }
                }
                if (StringUtils.isNotEmpty(station.getName())) {
                    response.setStationName(station.getName());
                }
                if (StringUtils.isNotEmpty(station.getCategory())) {
                    response.setStationType(station.getCategory());
                }
                if (StringUtils.isNotEmpty(station.getBrand())) {
                    response.setBrand(station.getBrand());
                }
                if (StringUtils.isNotEmpty(station.getContact())) {
                    response.setContactName(station.getContact());
                }
                if (station.getUser() != null && StringUtils.isNotEmpty(station.getUser().getUsername())) {
                    response.setMobilePhone(station.getUser().getUsername());
                }
            } else {
                response.setCity("");
                response.setStationName("");
                response.setStationType("");
                response.setBrand("");
                response.setContactName("");
                response.setMobilePhone("");
            }
            UserProfile userProfile = userProfileRepository.findByUserId(report.getRegularReport().getUser().getId());
            if (userProfile != null) {
                response.setUserName(userProfile.getRealName());
            } else {
                response.setUserName("");
            }
            colorAuditingReportsList.add(response);
        }
        return colorAuditingReportsList;
    }


    @ApiOperation("获取")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/getWarningReport", method = RequestMethod.GET)
    public JsonResponse getCustomerReport(Long loginUserId,
                                          Pageable pageable,
                                          @ApiParam("省") @RequestParam(value = "provinces", required = false) String province,
                                          @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
                                          @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brand,
                                          @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                                          @ApiParam("服务开始时间") @RequestParam(value = "serviceStartTime", required = false) Long serviceStartTime,
                                          @ApiParam("服务结束时间") @RequestParam(value = "serviceEndTime", required = false) Long serviceEndTime,
                                          @ApiParam("提交报告时间") @RequestParam(value = "startTime", required = false) Long startTime,
                                          @ApiParam("提交报告结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
                                          @ApiParam("外勤人员关键字") @RequestParam(value = "userName", required = false) String userName,
                                          @ApiParam("满意度打分") @RequestParam(value = "score", required = false) String score,
                                          @ApiParam("60分以下是否已处理") @RequestParam(value = "isManaged", required = false) String isManaged,
                                          @ApiParam(value = "维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
                                          @ApiParam(value = "部门ID") @RequestParam(value = "departmentId", required = false) Long departmentId,
                                          @ApiParam(value = "客户状态") @RequestParam(value = "customerStat", required = false) String customerStat,
                                          @ApiParam(value = "客户类型") @RequestParam(value = "customerType", required = false) String customerType,
                                          @ApiParam(value = "油漆品牌") @RequestParam(value = "paintBrand", required = false) String paintBrand,
                                          @ApiParam(value = "品牌定位") @RequestParam(value = "productPosition", required = false) String productPosition) {
//        isUserLogin();
        Page<CustomerRegularReport> reportList = customerService.getCustomerReport(loginUserId, pageable, province, category, brand, stationName, serviceStartTime,
                serviceEndTime, startTime, endTime, userName, score, isManaged, stationNum, departmentId, customerStat, customerType, paintBrand, productPosition);
        if (reportList == null) {
            return JsonResponse.errorResponseWithError("抱歉", "查询失败");
        }
        List<CustomerStatResponse> customerStatResponseList = new ArrayList<>();
        for (CustomerRegularReport customerRegularReport : reportList) {
            StationReport stationReport = stationReportRepository.selectReport(customerRegularReport.getRegularReport().getStation().getId());
            //查出服务人员姓名
            UserProfile realName = userProfileRepository.findByUserId(customerRegularReport.getRegularReport().getUser().getId());
            String serviceUserName = realName.getRealName();
            //查出客户姓名
            realName = userProfileRepository.findByUserId(customerRegularReport.getContactUser().getId());
            String customerUserName = realName.getRealName();
            CustomReportSms customReportSms = customReportSmsRepository
                .getSmsSendResultByCustomReportId(customerRegularReport.getId());
            CustomerStatResponse response = new CustomerStatResponse(customerRegularReport, serviceUserName, customerUserName,
                customReportSms == null ? (customerRegularReport.isSended() ? customerRegularReport.getCreationTime() : null) : customReportSms.getSendTime());
            //查出客户所在省份
            String customerProvince = customerRegularReport.getCustomerReport().getStation().getProvince();
            response.setProvice(customerProvince);
            //客户代码
            response.setStationNum(customerRegularReport.getRegularReport().getStation().getStationNum());
            //客户状态
            QuestionAnswerOption answer;
            StationColorReport stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 184L);
            if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationColorReport.getAnswerId()));
                if (null != answer && StringUtils.isNotEmpty(answer.getName())) {
                    response.setStationStatus(answer.getName());
                }
            }
            //客户类型
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 185L);
            if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationColorReport.getAnswerId()));
                if (null != answer && StringUtils.isNotEmpty(answer.getName())) {
                    response.setStationType(answer.getName());
                }
            }
            //具体品牌
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 8L);
            if (null != stationColorReport) {
                StringBuffer stringBuffer = new StringBuffer("");
                if (StringUtils.isNotEmpty(stationColorReport.getAnswerId())) {
                    String[] ids = stationColorReport.getAnswerId().split(",");
                    for (String id : ids) {
                        answer = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                        if (null != answer && StringUtils.isNotEmpty(answer.getName())) {
                            stringBuffer.append(answer.getName());
                        }
                    }
                }
                if (StringUtils.isNotEmpty(stationColorReport.getAnswerOther())) {
                    stringBuffer.append(stationColorReport.getAnswerOther());
                }
                response.setBrand(stringBuffer.toString());
            }
            //油漆服务商
            stationColorReport = stationColorReportRepository.selectReport(stationReport.getId(), 14L);
            if (null != stationColorReport && StringUtils.isNotEmpty(stationColorReport.getAnswerOther())) {
                response.setPaintService(stationColorReport.getAnswerOther());
            }
            //设置服务项目
            String[] serviceTypeIds = customerRegularReport.getRegularReport().getServiceTypAnswerIds().split(",");
            StringBuffer stringBuffer = new StringBuffer("");
            for (String id : serviceTypeIds) {
                if (StringUtils.isNotEmpty(id)) {
                    if (id.equals("191")) {
                        StationRegularServiceReport stationRegularServiceReport = stationRegularServiceReportRepository.selectQuestionOther(customerRegularReport.getRegularReport().getId(), 155L);
                        if (StringUtils.isNotEmpty(stationRegularServiceReport.getAnswerOther())) {
                            stringBuffer.append(stationRegularServiceReport.getAnswerOther() + ",");
                        }
                    }
                    answer = questionAnswerOptionRepository.findOne(Long.valueOf(id));
                    if (answer!=null&&answer.getName()!=null) {
                        stringBuffer.append(answer.getName() + ",");
                    }
                }
            }
            response.setServiceType(stringBuffer.toString());
            //设置服务结果
            StationRegularServiceReport stationRegularServiceReport = stationRegularServiceReportRepository.selectQuestionOther(customerRegularReport.getRegularReport().getId(), 156L);
            if (StringUtils.isNotEmpty(stationRegularServiceReport.getAnswerId())) {
                answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationRegularServiceReport.getAnswerId()));
                response.setServiceStat(answer.getName());
            }
            //设置服务人员自我评估
            stationRegularServiceReport = stationRegularServiceReportRepository.selectQuestionOther(customerRegularReport.getRegularReport().getId(), 157L);
            if (StringUtils.isNotEmpty(stationRegularServiceReport.getAnswerOther())) {
                response.setServicePoint(stationRegularServiceReport.getAnswerOther());
            }
            //设置客户职位
            if (StringUtils.isNotEmpty(realName.getPosition())) {
                response.setCustomerPosition(realName.getPosition());
            }
            //设置联系方式
            if (StringUtils.isNotEmpty(realName.getTelephone())) {
                response.setCustomerTelephone(realName.getTelephone());
            }
            //设置第一题分数
            StationCustomerReport stationCustomerReport = stationCustomerReportRepository.selectQuestion(customerRegularReport.getCustomerReport().getId(), 159L);
            answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationCustomerReport.getAnswerId()));
            response.setQuestionScore_1(answer.getName());
            //设置第二题分数
            stationCustomerReport = stationCustomerReportRepository.selectQuestion(customerRegularReport.getCustomerReport().getId(), 160L);
            answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationCustomerReport.getAnswerId()));
            response.setQuestionScore_2(answer.getName());
            //设置第三题分数
            stationCustomerReport = stationCustomerReportRepository.selectQuestion(customerRegularReport.getCustomerReport().getId(), 161L);
            answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationCustomerReport.getAnswerId()));
            response.setQuestionScore_3(answer.getName());
            //设置第四题分数
            stationCustomerReport = stationCustomerReportRepository.selectQuestion(customerRegularReport.getCustomerReport().getId(), 166L);
            answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationCustomerReport.getAnswerId()));
            response.setQuestionScore_4(answer.getName());
            //设置第五题分数
            stationCustomerReport = stationCustomerReportRepository.selectQuestion(customerRegularReport.getCustomerReport().getId(), 162L);
            answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationCustomerReport.getAnswerId()));
            response.setQuestionScore_5(answer.getName());
            //设置第六题分数
            stationCustomerReport = stationCustomerReportRepository.selectQuestion(customerRegularReport.getCustomerReport().getId(), 163L);
            answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationCustomerReport.getAnswerId()));
            response.setQuestionScore_6(answer.getName());
            //设置第七题分数
            stationCustomerReport = stationCustomerReportRepository.selectQuestion(customerRegularReport.getCustomerReport().getId(), 164L);
            answer = questionAnswerOptionRepository.findOne(Long.valueOf(stationCustomerReport.getAnswerId()));
            response.setQuestionScore_7(answer.getName());
            //设置处理的管理员
            User manageUser = customerRegularReport.getManageUser();
            String manageName = "";
            if (manageUser != null) {
                UserProfile manageProfile = userProfileRepository.findByUserId(manageUser.getId());
                if (manageProfile != null && StringUtils.isNotEmpty(manageProfile.getRealName())) {
                    manageName = manageProfile.getRealName();
                }
            }
            response.setManageName(manageName);
            customerStatResponseList.add(response);
        }
        Page<CustomerStatResponse> customerStatResponsePage = new PageImpl(customerStatResponseList, pageable, reportList.getTotalElements());
        return JsonResponse.successResponseWithPageData(customerStatResponsePage);
    }

    @ApiOperation("处理报告")
    @RequestMapping(value = "/manageReport", method = RequestMethod.POST)
    public JsonResponse manageReport(Long loginUserId,
                                     @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId,
                                     @ApiParam("处理内容") @RequestParam(value = "note") String note) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID错误");
        }
        if (StringUtils.isEmpty(note)) {
            return JsonResponse.errorResponseWithError("抱歉", "请填写处理记录");
        }
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.customerReport.id.eq(reportId));
        CustomerRegularReport customerRegularReport = customerRegularReportRepository.findOne(builder);
        if (customerRegularReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }
        Date date = new Date();
        customerRegularReport.setUpdateTime(date);
        customerRegularReport.setUpdateTimeStr(new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(date));
        customerRegularReport.setManageUser(user);
        customerRegularReport.setManaged(true);
        customerRegularReport.setManageNote(note);
        customerRegularReportRepository.save(customerRegularReport);
        CustomerManageNote customerManageNote = new CustomerManageNote();
        customerManageNote.setCustomerReport(customerRegularReport.getCustomerReport());
        customerManageNote.setManageUser(user);
        customerManageNote.setManageNote(note);
        customerManageNoteRepository.save(customerManageNote);
        try {
            Map<String, Object> data = new HashMap<>();
            data.put("str", note);
            userLogService.addUserLog(this.getCurrentUser(), customerRegularReport.getRegularReport().getStation().getStationNum(),
                    LogConstants.operate_type_manage_report,
                    LogConstants.business_type_customer_report, null, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResponse.successResponse();
    }

    @ApiOperation("获取处理记录列表")
    @RequestMapping(value = "/getManageRecorder", method = RequestMethod.GET)
    public JsonResponse getManageRecorder(Long loginUserId,
                                          @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId) {
        isUserLogin();
        User user = userRepository.findOne(loginUserId);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到当前登陆用户");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID错误");
        }
        QCustomerManageNote qCustomerManageNote = QCustomerManageNote.customerManageNote;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerManageNote.deleted.eq(false));
        builder.and(qCustomerManageNote.enabled.eq(true));
        builder.and(qCustomerManageNote.customerReport.id.eq(reportId));
        logger.info("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        List<CustomerManageNote> manageNoteList = (List<CustomerManageNote>) customerManageNoteRepository.findAll(builder);
        logger.info("-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-");
        List<String[]> manageList = toManageNoteResponse(manageNoteList);
        return JsonResponse.successResponseWithData(manageList);
    }

    private Logger logger = LoggerFactory.getLogger(WarningProcessing.class);

    private List<String[]> toManageNoteResponse(List<CustomerManageNote> manageNoteList) {
        List<String[]> strList = new ArrayList<>();
        for (CustomerManageNote note : manageNoteList) {
            User user = note.getManageUser();
            if (user == null) {
                continue;
            }
            UserProfile manageUser = userProfileRepository.findByUserId(user.getId());
            if (manageUser == null || StringUtils.isEmpty(manageUser.getRealName())) {
                continue;
            }
            String manageName = manageUser.getRealName();
            String manageTime = note.getCreationTimeStr();
            String manageNote = note.getManageNote();
            String[] manage = new String[3];
            manage[0] = manageName;
            manage[1] = manageTime;
            manageNote.replaceAll("<(S*?)[^>]*>.*?|<.*? />", "");
            manage[2] = manageNote;
            strList.add(manage);
        }
        return strList;
    }


}
